<template>
    <div>
        <div class="amap-x">
            <div :id='id'></div>
            <div class="change-layout" @click="select_layout=true">
                <template v-if="select_layout">
                    <div @click="layout=1" class="satellite" :class="{on: layout===1}">
                        <img src="../../../assets/images/star-tiles.png" alt="卫星地图">
                        <div>卫星地图</div>
                    </div>
                    <div @click="layout=2" class="street" :class="{on: layout===2}">
                        <img src="../../../assets/images/plan-tiles.png" alt="街道地图">
                        <div>街道地图</div>
                    </div>
                </template>
            </div>
        </div>
        <template v-if="edit">
            <div style='line-height: 50px;'>
                大致位置：{{click_address || '暂无'}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <template v-if="type === 1">预计面积：{{getAreaByPolygon}}平方公里</template>
                <template v-if="type === 2">预计长度：{{getLengthByPolyline}}公里</template>
                <template v-if="type === 3">描点个数：{{getPointNumByMarker}}个</template>
            </div>
            <div style="text-align: right;">
                <a-button @click="handle_clear" type='primary' style='margin-right: 12px;'>清除</a-button>
                <a-button @click="handle_update_address" type='primary'>确定</a-button>
            </div>
        </template>
    </div>
</template>

<script>
    export default {
        props: {
            type: {
                type: Number,
                default: () => (3)
            },
            update_address: {
                type: Function,
                default: () => {}
            },
            lng_lats: {
                type: String,
                default: () => ('')
            },
            edit: {
                type: Boolean,
                default: () => false
            },
            address: {
                type: String,
                default: () => ''
            },
            id: {
                type: String,
                default: () => 'search'
            }
        },
        data(){
            // 1: "面(平方公里)"
            // 2: "线(平方公里)"
            // 3: "点(每点*8h)"
            return {
                map: null,
                satellite: null,
                select_layout: false,
                layout: 1, //1：卫星图，2：街道图

                markers: [],
                click_address: '',

                polyline: null,
                polygon: null,

                positions: []
            }
        },
        computed: {
            getAreaByPolygon(){
                const { polygon } = this
                return polygon ? (polygon.getArea() / 1e6).toFixed(2)*1 : 0
            },
            getLengthByPolyline(){
                const { polyline } = this
                return polyline ? (polyline.getLength() / 1000).toFixed(2)*1 : 0
            },
            getPointNumByMarker(){
                const { markers } = this
                return markers.length
            },
        },
        watch: {
            layout(value){
                if(this.satellite){
                    value === 1?this.satellite.show():this.satellite.hide()
                }
            },
            lng_lats: {
                handler(value){
                    console.log(' --> lng_lats: ', value)
                    this.positions = value ? JSON.parse(value) : []
                },
                deep: true
            }
        },
        methods: {
            init_map(){
                // this.$nextTick( () => {
                // console.log(that.$refs.aa.innerText);  //输出：修改后的值
                    let el = document.getElementById(this.id)
                    console.log("el------>",el);
                    let map = this.map = new AMap.Map(this.id, {
                        resizeEnable: true,
                        zoom: 17
                    })
                    console.log("map--->",map);

                    this.geocoder = new AMap.Geocoder();

                    this.satellite = new AMap.TileLayer.Satellite({
                        map: map,
                    })
                    this.init_show()

                    if(this.edit){
                        this.init_event()
                    }
                // });
                
                
                

                
                // if(this.only_show){
                //     this.init_show()
                // }else{
                //     this.init_event()
                // }
                
            },
            init_event(){
                let { map, geocoder, type } = this
                console.log('this.address--->',this.address);
                
                if(map){
                    map.on('click', e => {
                        //点
                        this.add_marker(e.lnglat.getLng(), e.lnglat.getLat())

                        if(type === 2){
                            //线
                            this.add_polyline()
                        }

                        if(type === 1){
                            //面
                            //this.add_polyline()
                            this.add_polygon()
                        }

                        /*获取地址*/
                        geocoder.getAddress([e.lnglat.getLng(), e.lnglat.getLat()], (status, result) => {
                            if (status === 'complete' && result.info === 'OK') {
                                this.click_address = result.regeocode.formattedAddress
                            }
                        })
                    })
                }
                
            },

            init_show(){
                let { map, type, positions } = this

                console.log('type:', type, positions)

                if(positions && positions.length){
                    
                    if(type === 1){
                        //面
                        let polygon = this.add_polygon(positions)
                        map.setFitView([polygon])
                    }else if(type === 2){
                        let polyline = this.add_polyline(positions)
                        map.setFitView([polyline])
                    }else if(type === 3){
                        positions.forEach(pos => {
                            this.add_marker(pos.lng, pos.lat)
                        })
                        let { markers } = this
                        if(markers && markers.length){
                            map.setFitView(markers.map(item => item.marker))
                        }
                        
                    }
                }
            },

            add_marker(lng, lat){
                let marker = new AMap.Marker({
                    id: Math.random(),
                    position: new AMap.LngLat(lng, lat),
                    draggable: false,
                }).on('dragend', function (event) {
                    console.log(event)
                }); 
                this.markers.push({
                    marker: marker,
                    lng,
                    lat
                })
                this.map.add(marker)
                return marker
            },
            remove_marker(marker){
                this.map.remove(marker)
            },
            handle_clear(){
                let { map, markers, polyline, polygon } = this
                if(map){
                    this.markers.forEach(item => {
                        map.remove(item.marker)
                    })
                    this.markers = []
                    this.click_address = ''

                    if(polyline){
                        map.remove(polyline)
                        this.polyline = null
                    }
                    
                    if(polygon){
                        map.remove(polygon)
                        this.polygon = null
                    }

                    this.$message.success('清除成功', 1)
                }
            },

            add_polyline(list){
                const { map, markers } = this
                if(map){
                    this.remove_polyline()

                    let pathList = (list && list.length) ? list : markers

                    let path = pathList.map(item => new AMap.LngLat(item.lng, item.lat))
                    let polyline = new AMap.Polyline({
                        path: path,
                        borderWeight: 2, // 线条宽度，默认为 1
                        strokeColor: 'red', // 线条颜色
                        lineJoin: 'round' // 折线拐点连接处样式
                    })
                    this.polyline = polyline
                    map.add(polyline)
                    return polyline
                }
            },
            remove_polyline(){
                let { map, polyline } = this
                if(map && polyline){
                    map.remove(polyline)
                }
            },

            add_polygon(list){
                const { map, markers } = this
                if(map){
                    this.remove_polygon()

                    let pathList = (list && list.length) ? list : markers

                    let path = pathList.map(item => new AMap.LngLat(item.lng, item.lat))
                    let polygon = new AMap.Polygon({
                        path: path,
                        isOutline: true,
                        fillColor: '#1791fc', // 多边形填充颜色
                        fillOpacity: 0.4,
                        borderWeight: 2, // 线条宽度，默认为 1
                        strokeColor: "#FF33FF", // 线条颜色
                        strokeOpacity: 0.2,
                        strokeWeight: 6,
                    });
                    this.polygon = polygon
                    map.add(polygon)
                    return polygon
                }
            },
            remove_polygon(){
                let { map, polygon } = this
                if(map && polygon){
                    map.remove(polygon)
                }
            },

            handle_update_address(){
                let { markers, click_address, type, polygon, polyline } = this,
                    area = 0

                if(type === 3){
                    //点
                    area = markers.length || 0
                }else if(type === 2){
                    //线
                    // let lineLength = 0
                    // markers.forEach((item, index) => {
                    //     if (index % 2 !== 0 && index !== 0) {
                    //         lineLength += +AMap.GeometryUtil.distance(item.marker.getPosition(), markers[index - 1].marker.getPosition())
                    //     }
                    // })
                    // console.log('lineLength:', lineLength)
                    // area = lineLength ? (lineLength / 1000).toFixed(2)*1 : 0
                    area = polyline ? (polyline.getLength() / 1000).toFixed(2)*1 : 0
                }else if(type === 1){
                    //面
                    area = polygon ? (polygon.getArea() / 1e6).toFixed(2)*1 : 0
                }

                console.log('type:', type, ' area', area)
                this.update_address({
                    address: click_address,
                    area,
                    lng_lat: this.markers.map(item => ({ lng: item.lng, lat: item.lat}))
                })
            }
        },
        mounted(){

            this.markers = []
            this.positions = this.lng_lats ? JSON.parse(this.lng_lats) : []
            console.log("address--->",this.address);
            this.click_address = this.address;
            this.init_map()
        }
    }
</script>


<style lang="scss" scoped>
    .amap-x{
        position: relative;
        width: 800px;
        height: 600px;
        // #amap {
        //     position: absolute;
        //     top: 0;
        //     left: 0;
        //     width: 100%;
        //     height: 100%
        // }
        #search,#edit{
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%
        }
        .change-layout{
            position: absolute;
            top: 15px;
            right: 15px;
            opacity: 0.9;
            min-width: 44px;
            min-height: 44px;
            background: url('../../../assets/images/tiles-type.svg') center no-repeat;
            display: flex;
            align-items: center;
            .satellite, .street{
                background: #000;
                width: 80px;
                height: 100px;
                text-align: center;
                padding-top: 18px;
                &.on{
                    img{
                        border: 1px solid #1890ff;
                        //box-shadow: 0px 0px 4px 4px #1890ff inset;
                    }
                }
            }
        }
    }
</style>